package cn.weixindong.com.realm;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

public class webCustomRealm extends AuthorizingRealm {
	
	HashMap<String	, String> map = new HashMap<String, String>();
	{
		
		map.put("zhansan", "9dce278b2793adaa06cdd741a941e930");
		map.put("lisi", "12345");
		super.setName("webCustomRealm");
		
	}

	@Override
	/**
	 * 授权
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		
		String username = (String) principals.getPrimaryPrincipal();
		Set<String> roles = getRolesByUserName(username);
		Set<String> permissions = getPermissionsByUserName(username);
		
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.setRoles(roles);
		authorizationInfo.setStringPermissions(permissions);
		return authorizationInfo;
	}

	@Override
	
	/**
	 * 登陆认证
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		String 	 username = (String) token.getPrincipal();
		String password = getPasswordByUserName(username);
		if(password==null){
			return null;
		}
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username,password,"webCustomRealm");
		//密码加盐
		authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(username));
		return authenticationInfo;
	}
	
	/**
	 * 根据名字获取密码
	 * @param username
	 * @return
	 */
	private String getPasswordByUserName(String username){
		return map.get(username);
	}
	
	
	private Set<String> getRolesByUserName(String username){
		HashSet<String> hashSet = new HashSet<String>();
		hashSet.add("admin");
		hashSet.add("user");
		return hashSet;
		
	}
	
	private Set<String> getPermissionsByUserName(String username){
		HashSet<String> hashSet = new HashSet<String>();
		hashSet.add("user:add");
		hashSet.add("user:delete");
		return hashSet;
		
		
		
	}
	
	public static void main(String[] args) {
		Md5Hash md5Hash = new Md5Hash("12343","zhansan");
		System.out.println(md5Hash.toString());
		
	}

}
